package com.example.demo2.controller;

import com.example.demo2.entity.*;
import com.example.demo2.mapper.*;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;



import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@CrossOrigin
public class RegulationController {

    @Autowired
    ComparisonMapper comparisonMapper;
    @Autowired
    ProjectMapper projectMapper;
    @Autowired
    StandardMapper standardMapper;
    @Autowired
    ProgramMapper programMapper;

    private ConcurrentHashMap<String, Integer> concurrentMap;

    @Autowired
    public void MyController(ConcurrentHashMap<String, Integer> concurrentMap) {
        this.concurrentMap = concurrentMap;
    }

    //检测人员所有比对测试
    @GetMapping("/findComparisonByUID")
    public List<Comparison> findComparisonByUID() {
        Integer uID = (Integer) concurrentMap.get("uID");
        List<Comparison> comparisons=comparisonMapper.findComparisonByUID(uID);
        for(Comparison comparison:comparisons){
            Integer pjId=comparison.getPjId();
            Project project=projectMapper.findProjectByPjId(pjId);
            if(project!=null){
                comparison.setPjName(project.getPjName());
                Standard standard=standardMapper.findStandardByStaId(project.getStaId());
                comparison.setStaName(standard.getStaName());
            }
        }
        return comparisons;
    }

    @GetMapping("/findComparisonNumByUID")
    public int findComparisonNumByUID() {

        Integer uID = (Integer) concurrentMap.get("uID");
        List<Comparison> comparisons=comparisonMapper.findComparisonByUID(uID);
        return comparisons.size();
    }

    //根据项目找比对测试方案
    @GetMapping("/findProgramByPjId/{pjId}")
    public List<Program> findProgramByPjId(@PathVariable int pjId) {
        String pgType = "比对方案";
        return programMapper.findProgramByPjId(pjId,pgType);
    }

    //根据项目找操作规程
    @GetMapping("/findPgByPjId/{pjId}")
    public List<Program> findPgByPjId(@PathVariable int pjId) {
        String pgType = "操作规程";
        return programMapper.findProgramByPjId(pjId,pgType);
    }

    //下载操作规程/比对方案
    @GetMapping("/downloadProgram/{pgId}")
    public String downloadProgram(@PathVariable int pgId)
    {
        return programMapper.findPgUrlByPgId(pgId);

    }

    //提交比对申请
    @PutMapping("/addComparison/{pjId}")
    public String addComparison( @PathVariable int pjId) {
        Integer uID = (Integer) concurrentMap.get("uID");
        if(uID==null) {
            return "请先跳转登录";
        }
        else
        {
            Comparison comparison=comparisonMapper.searchComparisonByPjId(uID,pjId);
            if(comparison==null) {
                comparison=new Comparison();
                Date now = new Date();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String startDate = dateFormat.format(now);
                comparison.setUID(uID);
                comparison.setPjId(pjId);
                comparison.setStartDate(startDate);
                comparisonMapper.insertComparison(comparison);
                return "申请成功";
            }
            else
            {
                return "您已申请";
            }
        }
    }

    //个人比对申请搜索
    @GetMapping("/searchComparison")
    public List<Comparison> searchComparison(@RequestParam(value = "info", required = false) String info,
                                             @RequestParam(value = "year", required = false) String year,
                                             @RequestParam(value = "month", required = false) String month,
                                             @RequestParam(value = "day", required = false) String day) {
        Integer uID = (Integer) concurrentMap.get("uID");
        if(uID==null) {
            return null;
        }
        List<Project> retList = new ArrayList<>();
        List<Standard> retStandard = new ArrayList<>();
        List<Comparison> retComparison = new ArrayList<>();
        if(info!=null && !info.equals(""))
        {
            String query = "%" + info + "%";
            retList = projectMapper.searchProject(query);
            retStandard = standardMapper.searchStandard(query);
            for (Standard standard : retStandard) {
                List<Project> projects = projectMapper.findAllProjectBysatId(standard.getStaId());
                for (Project project : projects) {
                    if(!retList.contains(project)){
                        retList.add(project);
                    }
                }
            }
            for(Project project:retList){
                Comparison comparison= comparisonMapper.searchComparisonByPjId(uID,project.getPjId());
                if(comparison!=null){
                    retComparison.add(comparison);
                }
            }
        }
        if(year!=null&& !year.equals(""))
        {
            String query = "%" + year;
            if(month!=null && !month.equals(""))
            {
                query = query +"-"+ month;
                if(day!=null && !day.equals(""))
                {
                    query = query +"-"+ day;
                }
                else {
                    query = query + "%";
                }
            }
            else {
                query = query + "%";
            }
            List<Comparison> comparisons = comparisonMapper.searchComparisonByStartDate(uID,query);
            if(!comparisons.isEmpty())
            {
                if(!retComparison.isEmpty())
                {
                    for (Comparison comparison : comparisons) {
                        boolean exists = false;
                        for (Comparison comparison1 : retComparison) {
                            if(comparison1.getPjId()==comparison.getPjId()){
                                exists = true;
                                break;
                            }
                        }
                        if (!exists)
                        {
                            retComparison.add(comparison);
                        }
                    }
                }
                else {
                    retComparison = comparisons;
                }
            }
        }
        for(Comparison comparison:retComparison){
            Integer pjId=comparison.getPjId();
            Project project=projectMapper.findProjectByPjId(pjId);
            if(project!=null){
                comparison.setPjName(project.getPjName());
                Standard standard=standardMapper.findStandardByStaId(project.getStaId());
                comparison.setStaName(standard.getStaName());
            }
        }
        return retComparison;
    }

    /*@PutMapping("/excelAddToStandard")
    public int excelAddToStandard(@RequestParam MultipartFile formData)throws Exception {

        InputStream inputStream = formData.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        List<List<Object>> rows = reader.read();
        //System.out.println("UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"+rows);
        //System.out.println("YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY"+rows.get(0).get(0));
        List<Standard> standards = new ArrayList<>();
        List<Project> projects = new ArrayList<>();

        boolean flag = false;

        //开始导入标准表单
        for (List<Object> row : rows) {
            if (standards.isEmpty() && row != null && !row.isEmpty() && !flag) {
                flag = true;
                System.out.println("UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU");
                continue; // 跳过标题行
            }
            Standard standard = new Standard();
            standard.setStaName(row.get(1).toString()); // 假设类别(产品/项目/参数)和标准名称在第二列
            standard.setStaGB(row.get(4).toString()); // 假设标准编号（含年号）在第五列
            standard.setStaClause(row.get(5).toString());//假设条款号在第六列
            standard.setStaAllGB(row.get(4).toString() + " " + row.get(5).toString());

            Project project = new Project();
            project.setPjName(row.get(2).toString());
            project.setPjGB(row.get(4).toString() + " " + row.get(5).toString());
            //寻找到staID根据GB

            String category = row.get(0).toString(); // 假设大类在第一列
            if ("无源医疗器械".equals(category)) {
                standard.setStaType(0);
            } else if ("有源医疗器械".equals(category)) {
                standard.setStaType(1);
            }

            standards.add(standard);
        }

        //System.out.println("UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"+standards);
        standardMapper.insertStandardList(standards);

        //开始导入项目
        flag = false;

        for (List<Object> row : rows) {

            if (projects.isEmpty() && row != null && !row.isEmpty() && !flag) {
                flag = true;
                System.out.println("222222222222222222222222222222222222222222222222222222222");
                continue; // 跳过标题行
            }
//            Standard standard = new Standard();
//            standard.setStaName(row.get(1).toString()); // 假设类别(产品/项目/参数)和标准名称在第二列
//            standard.setStaGB(row.get(4).toString()); // 假设标准编号（含年号）在第五列
//            standard.setStaClause(row.get(5).toString());//假设条款号在第六列
//            standard.setStaAllGB(row.get(4).toString()+" "+row.get(5).toString());

            Project project = new Project();
            project.setPjName(row.get(2).toString());
            String staGB = row.get(4).toString() + " " + row.get(5).toString();
            project.setPjGB(staGB);
            //寻找到staID根据GB
            int staId = projectMapper.findStaIdByGB(staGB);
            project.setStaId(staId);
            projects.add(project);
        }


        return projectMapper.insertProjectList(projects);

    }*/

}
